package weather.com.weather

import android.content.ContentValues
import android.content.DialogInterface
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.support.v7.app.AlertDialog
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.view.View
import android.widget.*
import com.google.gson.Gson
import kotlinx.android.synthetic.main.activity_city_control.*
import kotlinx.android.synthetic.main.title_bar.*
import okhttp3.*
import org.litepal.LitePal
import weather.com.weather.adapter.CityListAdapter
import weather.com.weather.bean.CityListBean
import weather.com.weather.bean.WeatherBean
import java.io.IOException
import java.net.SocketTimeoutException
import java.util.concurrent.TimeUnit

class CityControl : AppCompatActivity(), View.OnClickListener,AdapterView.OnItemClickListener,AdapterView.OnItemLongClickListener {
    override fun onItemLongClick(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long): Boolean {
        //TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
        AlertDialog.Builder(this@CityControl)
                .setMessage("是否删除该城市")
                .setPositiveButton("删除", DialogInterface.OnClickListener { dialogInterface, i ->
                    var s = LitePal.where("city = ?",p1!!.findViewById<TextView>(R.id.city_name).text.toString()).find(CityListBean::class.java)
                    LitePal.delete(CityListBean::class.java,s[0].id)
                    lis = LitePal.findAll(CityListBean::class.java)
                    city_list.adapter = CityListAdapter(this@CityControl, lis)
                }).show()
        return false
    }

    var lis = listOf<CityListBean>()//创建一个ArrayList用来保存选择的城市信息
    //TODO(点击item传城市名回去显示选择城市信息)
    val h = object : Handler() {
        override fun handleMessage(msg: Message?) {
            super.handleMessage(msg)
            when (msg!!.what) {
                0 -> {
                    /**
                     * 解析Json数据
                     */
                    Log.d("Handler检查数据", msg.data.getString("data"))
                    var res = Gson().fromJson(msg.data.getString("data"), WeatherBean::class.java)
                    Log.d("请求回来的数据", res.toString())
                    if (res.reason == "查询不到该城市的信息") {
                        Toast.makeText(this@CityControl, "无效城市名", Toast.LENGTH_SHORT).show()
                    } else {
                        var d = LitePal.where("city = ?", res.result.today.city).find(CityListBean::class.java)
                        if (d.size==0) {
                            CityListBean(res.result.today.city, res.result.today.temperature, res.result.today.weather).save()
                            lis = LitePal.findAll(CityListBean::class.java)
                            city_list.adapter = CityListAdapter(this@CityControl, lis)
                        } else {
                            AlertDialog.Builder(this@CityControl)
                                    .setMessage("城市已存在，是否更新数据？")
                                    .setPositiveButton("更新", DialogInterface.OnClickListener { dialogInterface, i ->
                                        var cv = ContentValues()
                                        cv.put("city",res.result.today.city)
                                        cv.put("temperature",res.result.today.temperature)
                                        cv.put("weather",res.result.today.weather)
                                        Log.d("测试数据库信息",d.toString())
                                        LitePal.update(CityListBean::class.java,cv,d[0].id)
                                    }).show()
                        }
                    }
                    Toast.makeText(this@CityControl, "请求完成", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_city_control)
//        LitePal.deleteAll(CityListBean::class.java)
//        LitePal.where("city = ?","广州").find(CityListBean::class.java)
        lis = LitePal.findAll(CityListBean::class.java)

        var list = findViewById<ListView>(R.id.city_list)
        city_list.adapter = CityListAdapter(this, lis)
        add_city.setOnClickListener(this)
        city_list.setOnItemClickListener(this)
        city_list.setOnItemLongClickListener(this)
        complete.setOnClickListener(this)
        //TODO("创建数据库表用来保存城市信息，一次请求完毕")

    }

    override fun onItemClick(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) {
        //TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
        var textd = p1!!.findViewById<TextView>(R.id.city_name).text
        AlertDialog.Builder(this)
                .setMessage("确定更换成该城市的详细信息吗")
                .setPositiveButton("确认", DialogInterface.OnClickListener { dialogInterface, i ->
                    var intent: Intent = getIntent()
                    intent.putExtra("cityname",textd.toString())
                    setResult(0,intent)
                    finish()
                }).show()
    }

    override fun onClick(p0: View?) {
        //TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
        when (p0!!.id) {
            R.id.add_city -> {
                var et = EditText(this)
                et.maxLines = 1
                AlertDialog.Builder(this@CityControl)
                        .setTitle("城市名")
                        .setView(et)
                        .setPositiveButton("确定", DialogInterface.OnClickListener { dialogInterface, i ->
                            if (et.text != null && et.text.toString()!="") {
                                var url = "http://v.juhe.cn/weather/index?format=2&dtype=&cityname=${et.text}&key=7a819e323bd6fc0f75d1f9f6e6cecc47"

                                Thread(object : Runnable {
                                    override fun run() {
                                        var client = OkHttpClient.Builder().connectTimeout(10, TimeUnit.SECONDS).build() //创建对象

                                        var request = Request.Builder().url(url).build()//建立连接
                                        var call = client.newCall(request)
                                        call.enqueue(object : Callback{
                                            override fun onFailure(call: Call?, e: IOException?) {
                                                // TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
                                                if(e is SocketTimeoutException){//判断超时异常
                                                    Toast.makeText(this@CityControl,"请求超时",Toast.LENGTH_SHORT).show()
                                                }
                                            }
                                            override fun onResponse(call: Call?, response: Response?) {
                                                // TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
                                                var data: String = response!!.body()!!.string()
//                                                Log.d("测试返回的数据", data)
                                                var bundle = Bundle()//创建Bundle对象用来存储数据
                                                bundle.putString("data", data)//给bundle设置数据
                                                var me = Message.obtain()
                                                me.data = bundle//
                                                me.what = 0
                                                h.sendMessage(me)
                                            }
                                        })
                                    }
                                }).start()
                            }else{
                                Toast.makeText(this,"无效城市",Toast.LENGTH_SHORT).show()
                            }
                        }).show()
            }
            R.id.complete -> {
                finish()
            }
        }
    }

}
